<template>
  <div class="customer-data-generator">
    <el-card class="generator-card">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><DataAnalysis /></el-icon>
            客户数据获取
          </span>
          <el-tag type="success" size="small">从公司API获取数据</el-tag>
        </div>
      </template>

      <div class="generator-content">
        <!-- 说明信息 -->
        <el-alert
          title="数据获取说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>• 从公司客户管理系统API获取最新客户数据</p>
            <p>• 每次获取 1000-2000 条客户记录（根据系统当前数据量）</p>
            <p>• 包含完整的客户信息：基本信息、服务详情、合同状态、费用记录等</p>
            <p>• 自动同步客户标签和风险评估数据</p>
            <p>• 数据获取过程中会进行数据清洗和格式化处理</p>
          </template>
        </el-alert>

        <!-- 获取按钮区域 -->
        <div class="generator-actions">
          <el-button
            type="primary"
            size="large"
            :loading="generating"
            :disabled="generating"
            @click="generateCustomerData"
          >
            <el-icon v-if="!generating"><Refresh /></el-icon>
            {{ generating ? '正在获取数据...' : '获取客户数据' }}
          </el-button>

          <el-button
            type="success"
            size="large"
            :disabled="!lastGenerationResult"
            @click="viewGeneratedData"
          >
            <el-icon><View /></el-icon>
            查看获取结果
          </el-button>
        </div>

        <!-- 进度显示 -->
        <div v-if="generating" class="progress-section">
          <el-progress
            :percentage="progressPercentage"
            :status="progressStatus"
            :stroke-width="8"
          />
          <p class="progress-text">{{ progressText }}</p>
        </div>

        <!-- 获取结果 -->
        <div v-if="lastGenerationResult" class="result-section">
          <el-card class="result-card">
            <template #header>
              <span class="result-title">
                <el-icon><SuccessFilled /></el-icon>
                最近获取结果
              </span>
            </template>

            <div class="result-stats">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-statistic
                    title="获取客户数"
                    :value="lastGenerationResult.generated_count"
                    suffix="条"
                  >
                    <template #prefix>
                      <el-icon style="vertical-align: -0.125em">
                        <User />
                      </el-icon>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="8">
                  <el-statistic
                    title="同步标签数"
                    :value="lastGenerationResult.tag_count"
                    suffix="个"
                  >
                    <template #prefix>
                      <el-icon style="vertical-align: -0.125em">
                        <PriceTag />
                      </el-icon>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="8">
                  <el-statistic
                    title="获取耗时"
                    :value="generationTime"
                    suffix="秒"
                  >
                    <template #prefix>
                      <el-icon style="vertical-align: -0.125em">
                        <Timer />
                      </el-icon>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
            </div>

            <!-- 样例数据展示 -->
            <div v-if="lastGenerationResult.sample_customers" class="sample-data">
              <h4>获取数据预览（前10条）：</h4>
              <el-table
                :data="lastGenerationResult.sample_customers"
                size="small"
                stripe
                style="width: 100%"
              >
                <el-table-column prop="customer_id" label="客户ID" width="120" />
                <el-table-column prop="gender" label="性别" width="80">
                  <template #default="scope">
                    <el-tag :type="scope.row.gender === 'Male' ? 'primary' : 'danger'" size="small">
                      {{ scope.row.gender === 'Male' ? '男' : '女' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="churn_risk" label="风险等级" width="100">
                  <template #default="scope">
                    <el-tag
                      :type="getRiskTagType(scope.row.churn_risk)"
                      size="small"
                    >
                      {{ getRiskLabel(scope.row.churn_risk) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="monthly_charges" label="月费用" width="100">
                  <template #default="scope">
                    ¥{{ scope.row.monthly_charges.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.created_at) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  DataAnalysis,
  Refresh,
  View,
  SuccessFilled,
  User,
  PriceTag,
  Timer
} from '@element-plus/icons-vue'
import { generateRandomCustomers } from '@/api/modules/customer'
import { useRouter } from 'vue-router'

const router = useRouter()

// 组件挂载时的初始化
onMounted(() => {
  console.log('客户数据获取组件已挂载')
  // 重置所有状态
  generating.value = false
  progressPercentage.value = 0
  progressText.value = ''
})

// 组件卸载时的清理
onUnmounted(() => {
  console.log('客户数据获取组件已卸载')
})

// 响应式数据
const generating = ref(false)
const progressPercentage = ref(0)
const progressStatus = ref('')
const progressText = ref('')
const lastGenerationResult = ref(null)
const generationTime = ref(0)

// 计算属性 - 暂时移除未使用的计算属性

// 获取客户数据
const generateCustomerData = async () => {
  try {
    // 确认操作
    await ElMessageBox.confirm(
      '确定要从公司API获取最新客户数据吗？这将同步1000-2000条客户记录到本地数据库。',
      '确认获取数据',
      {
        confirmButtonText: '确定获取',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    generating.value = true
    progressPercentage.value = 0
    progressText.value = '正在连接公司API...'
    
    const startTime = Date.now()

    // 模拟进度更新
    const progressInterval = setInterval(() => {
      if (progressPercentage.value < 90) {
        progressPercentage.value += Math.random() * 10
        if (progressPercentage.value < 30) {
          progressText.value = '正在获取客户基本信息...'
        } else if (progressPercentage.value < 60) {
          progressText.value = '正在同步服务和合同数据...'
        } else if (progressPercentage.value < 90) {
          progressText.value = '正在处理费用和风险评估数据...'
        }
      }
    }, 200)

    // 调用API获取数据
    const response = await generateRandomCustomers()

    clearInterval(progressInterval)
    progressPercentage.value = 100
    progressText.value = '数据获取完成！'
    
    const endTime = Date.now()
    generationTime.value = ((endTime - startTime) / 1000).toFixed(2)

    if (response.success) {
      lastGenerationResult.value = response.data
      ElMessage.success(response.message)
    } else {
      throw new Error(response.message || '获取数据失败')
    }

  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('获取客户数据失败:', error)
      ElMessage.error(error.message || '获取客户数据失败')
    }
  } finally {
    generating.value = false
    setTimeout(() => {
      progressPercentage.value = 0
      progressText.value = ''
    }, 2000)
  }
}

// 查看获取的数据
const viewGeneratedData = () => {
  router.push('/customer/list')
}

// 获取风险等级标签类型
const getRiskTagType = (risk) => {
  switch (risk) {
    case 'high': return 'danger'
    case 'medium': return 'warning'
    case 'low': return 'success'
    default: return 'info'
  }
}

// 获取风险等级标签文本
const getRiskLabel = (risk) => {
  switch (risk) {
    case 'high': return '高风险'
    case 'medium': return '中风险'
    case 'low': return '低风险'
    default: return '未知'
  }
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}
</script>

<style scoped>
.customer-data-generator {
  padding: 20px;
}

.generator-card {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.generator-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.generator-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin: 24px 0;
}

.progress-section {
  text-align: center;
  margin: 24px 0;
}

.progress-text {
  margin-top: 12px;
  color: #606266;
  font-size: 14px;
}

.result-section {
  margin-top: 24px;
}

.result-card {
  border: 1px solid #e4e7ed;
}

.result-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #67c23a;
}

.result-stats {
  margin-bottom: 24px;
}

.sample-data h4 {
  margin: 16px 0 12px 0;
  color: #303133;
  font-size: 16px;
}

:deep(.el-statistic__content) {
  font-size: 24px;
}

:deep(.el-statistic__title) {
  font-size: 14px;
  color: #909399;
}
</style>
